import { useMemberStore } from '@/stores'

let socketTask: null | UniApp.SocketTask = null
let reconnectAttempts = 0
const MAX_RECONNECT_ATTEMPTS = 5

export function initWebSocket() {
  const authStore = useMemberStore()

  if (socketTask || !authStore.getToekn()) return

  socketTask = uni.connectSocket({
    url: `ws://192.168.1.34:8000/ws/balance/?token=${authStore.getToekn()}`,
    success: () => {
      console.log('WebSocket连接创建成功')
    },
  })

  uni.onSocketOpen(() => {
    reconnectAttempts = 0
    console.log('WebSocket已连接')
  })

  uni.onSocketMessage((res) => {
    const data = JSON.parse(res.data)
    console.log('WebSocket收到消息:', data)
    authStore.updateBalance(res.data)
  })

  uni.onSocketError((error) => {
    console.error('WebSocket错误:', error)
    reconnect()
  })

  uni.onSocketClose(() => {
    console.log('WebSocket已断开')
    reconnect()
  })
}

function reconnect() {
  if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
    setTimeout(() => {
      reconnectAttempts++
      initWebSocket()
    }, 3000)
  }
}
export function getBalanceSocket(): boolean {
  if (socketTask) {
    return true
  }
  return false
}
export function closeWebSocket() {
  if (socketTask) {
    socketTask.close({})
    socketTask = null
  }
}
